<?php
namespace app\index\logic;

use think\facade\Db;
use app\index\validate\Index as indexValidate;

class Index
{
    public function index($site, $lang)
    {
        $temp = Db::name('category')->where('site_id', $site['id'])->where('language_id', $lang)->column('id');
        // 取所有文章列表
        $list = Db::name('article')
            ->alias('a')
            ->join('category c', 'a.category_id = c.id')
            ->where('a.category_id', 'in', $temp)
            ->field('a.*, c.title as category_name')
            ->order('a.id desc')
            ->paginate(10)->toArray();
        return $list;
    }

    public function category($site, $lang)
    {
        $validate = new indexValidate();
        if(!$validate->scene('category')->check(input('get.'))){
            return [
                'code' => 10001,
                'msg' => $validate->getError()
            ];
        }
        $category = Db::name('category')
            ->where('id', input('get.category_id'))
            ->find();
        if($category['category_type'] == 1){
            $tpl = 'category';
        }else{
            $tpl = 'category_single';
        }
        return [
            'code' => 10000,
            'tpl' => $tpl,
            'list' => $category['category_type'] == 1 ? $this->index($site, $lang) : [],
            'category' => $category
        ];
    }

    public function detail()
    {
        $validate = new indexValidate();
        if(!$validate->scene('detail')->check(input('get.'))){
            return [
                'code' => 10001,
                'msg' => $validate->getError()
            ];
        }
        $id = input('get.detail_id');
        $detail = Db::name('article')
            ->where('id', $id)
            ->find();
        if(is_object($detail)){
            $detail = $detail->toArray();
        }
        return [
            'code' => 10000,
            'detail' => $detail
        ];
    }
}